package com.doodle.common.widget;

import android.content.Context;
import android.graphics.PointF;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

/**
 * 注内部事件处理，其itemView的顶层view需是HeaderFooterContainer类型
 * @author mason
 *
 */
public class ChildViewPager extends ViewPager {
	
	private int mTouchSlop = 0;

	public ChildViewPager(Context context, AttributeSet attrs) {
		super(context, attrs);
        final ViewConfiguration configuration = ViewConfiguration.get(getContext());
        mTouchSlop = configuration.getScaledTouchSlop();
	}

	public ChildViewPager(Context context) {
		super(context);
        final ViewConfiguration configuration = ViewConfiguration.get(getContext());
        mTouchSlop = configuration.getScaledTouchSlop();
	}

	private PointF downPoint = new PointF();
	private boolean touchItem = true;
	
	@Override
	public boolean onInterceptTouchEvent(MotionEvent arg0) {
		getParent().requestDisallowInterceptTouchEvent(true);
		return super.onInterceptTouchEvent(arg0);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		
		int oldX = getScrollX();
		boolean handle = super.onTouchEvent(event);
		int newX = getScrollX();
		if (oldX != newX) {
			getParent().requestDisallowInterceptTouchEvent(true);
		} 
		
		for (int i = 0; i < getChildCount(); i++) {
			View itemView = getChildAt(i);
			if (itemView.getTag() instanceof Integer) {
				int position = (Integer) itemView.getTag();
				if (position == getCurrentItem()) {
					switch (event.getAction()) {
						case MotionEvent.ACTION_DOWN:
							touchItem = true;
							downPoint.x = event.getX();
							downPoint.y = event.getY();
							break;
						case MotionEvent.ACTION_MOVE:
							float dx = Math.abs(event.getX() - downPoint.x);
							float dy = Math.abs(event.getY() - downPoint.y);
							
							if (dx > dy && dx > mTouchSlop && touchItem) {
								touchItem = false;
								event.setAction(MotionEvent.ACTION_CANCEL);
								itemView.dispatchTouchEvent(event);
							}
							break;
					}
					if (touchItem) {
						itemView.dispatchTouchEvent(event);
					}
					break;
				}
			}
		}
		
		return handle;
	}
}
